package com.example.note;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import java.io.File;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.lifecycle.ViewModelProvider;

import com.bumptech.glide.Glide;
import com.example.note.activity.DiaryEditActivity;
import com.example.note.database.DiaryEntity;
import com.example.note.view.HandwritingView;
import com.example.note.viewmodel.DiaryViewModel;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

public class DiaryReadActivity extends AppCompatActivity {
    
    public static final String EXTRA_DIARY_ID = "diary_id";
    
    private DiaryViewModel diaryViewModel;
    private DiaryEntity currentDiary;
    private MediaPlayer mediaPlayer; // 音乐播放器
    
    private TextView tvTitle;
    private TextView tvDate;
    private TextView tvTime;
    private TextView tvMood;
    private TextView tvWeather;
    private TextView tvContent;
    private TextView tvTimestamp;
    private ImageView ivMood;
    private ImageView ivWeather;
    private ImageView ivImage;
    private HandwritingView handwritingView;
    private ImageButton btnEdit;
    private Button btnShare;
    private Button btnDelete;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_diary_read);
        
        initViews();
        setupToolbar();
        setupViewModel();
        loadDiaryData();
        setupEventListeners();
    }
    
    private void initViews() {
        tvTitle = findViewById(R.id.tv_title);
        tvDate = findViewById(R.id.tv_date);
        tvTime = findViewById(R.id.tv_time);
        tvMood = findViewById(R.id.tv_mood);
        tvWeather = findViewById(R.id.tv_weather);
        tvContent = findViewById(R.id.tv_content);
        tvTimestamp = findViewById(R.id.tv_timestamp);
        ivMood = findViewById(R.id.iv_mood);
        ivWeather = findViewById(R.id.iv_weather);
        ivImage = findViewById(R.id.iv_image);
        handwritingView = findViewById(R.id.handwriting_view);
        btnEdit = findViewById(R.id.btn_edit);
        btnShare = findViewById(R.id.btn_share);
        btnDelete = findViewById(R.id.btn_delete);
    }
    
    private void setupToolbar() {
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        
        toolbar.setNavigationOnClickListener(v -> finish());
    }
    
    private void setupViewModel() {
        diaryViewModel = new ViewModelProvider(this).get(DiaryViewModel.class);
    }
    
    private void loadDiaryData() {
        long diaryId = getIntent().getLongExtra(EXTRA_DIARY_ID, -1);
        if (diaryId == -1) {
            Toast.makeText(this, "日记不存在", Toast.LENGTH_SHORT).show();
            finish();
            return;
        }
        
        diaryViewModel.getDiaryById((int) diaryId).observe(this, diary -> {
            if (diary != null) {
                currentDiary = diary;
                populateViews(diary);
            } else {
                Toast.makeText(this, "日记不存在", Toast.LENGTH_SHORT).show();
                finish();
            }
        });
    }
    
    private void populateViews(DiaryEntity diary) {
        tvTitle.setText(diary.getTitle());
        
        // 根据输入模式显示内容
        if ("handwriting".equals(diary.getInputMode()) && !TextUtils.isEmpty(diary.getHandwritingPath())) {
            // 显示手写内容
            tvContent.setVisibility(View.GONE);
            handwritingView.setVisibility(View.VISIBLE);
            
            // 延迟加载手写内容，确保View已经完成布局
            handwritingView.post(new Runnable() {
                @Override
                public void run() {
                    loadHandwritingFromFile(diary.getHandwritingPath());
                }
            });
        } else {
            // 显示文本内容
            tvContent.setVisibility(View.VISIBLE);
            handwritingView.setVisibility(View.GONE);
            tvContent.setText(diary.getContent());
        }
        
        // 格式化日期和时间
        tvDate.setText(diary.getDate());
        tvTime.setText(diary.getTime());
        
        // 设置心情
        setMoodDisplay(diary.getMood());
        
        // 设置天气
        setWeatherDisplay(diary.getWeather());
        
        // 设置图片 - 修改逻辑，确保图片不会遮挡手写内容
        if (diary.getImagePath() != null && !diary.getImagePath().isEmpty()) {
            ivImage.setVisibility(View.VISIBLE);
            Glide.with(this)
                    .load(diary.getImagePath())
                    .centerCrop()
                    .error(R.drawable.ic_image) // 添加错误占位符
                    .into(ivImage);
        } else {
            ivImage.setVisibility(View.GONE);
        }
        
        // 设置时间戳
        SimpleDateFormat timestampFormat = new SimpleDateFormat("创建于 yyyy-MM-dd HH:mm", Locale.getDefault());
        tvTimestamp.setText(timestampFormat.format(new Date(diary.getTimestamp())));
        
        // 自动播放背景音乐
        playBackgroundMusic(diary.getBackgroundMusicPath());
    }
    
    private void setMoodDisplay(String mood) {
        tvMood.setText(mood);
        
        int moodIcon;
        switch (mood) {
            case "开心":
                moodIcon = R.drawable.ic_mood_happy;
                break;
            case "难过":
                moodIcon = R.drawable.ic_mood_sad;
                break;
            case "平静":
                moodIcon = R.drawable.ic_mood_neutral;
                break;
            default:
                moodIcon = R.drawable.ic_mood_neutral;
                break;
        }
        
        ivMood.setImageResource(moodIcon);
    }
    
    private void setWeatherDisplay(String weather) {
        tvWeather.setText(weather);
        
        int weatherIcon;
        switch (weather) {
            case "晴天":
                weatherIcon = R.drawable.ic_weather_sunny;
                break;
            case "多云":
                weatherIcon = R.drawable.ic_weather_cloudy;
                break;
            case "雨天":
                weatherIcon = R.drawable.ic_weather_rainy;
                break;
            default:
                weatherIcon = R.drawable.ic_weather_sunny;
                break;
        }
        
        ivWeather.setImageResource(weatherIcon);
    }
    
    private void setupEventListeners() {
        // 编辑按钮
        btnEdit.setOnClickListener(v -> {
            Intent intent = new Intent(this, DiaryEditActivity.class);
            intent.putExtra(DiaryEditActivity.EXTRA_DIARY_ID, (long) currentDiary.getId());
            startActivity(intent);
        });
        
        // 分享按钮
        btnShare.setOnClickListener(v -> shareDiary());
        
        // 删除按钮
        btnDelete.setOnClickListener(v -> showDeleteConfirmDialog());
        
        // 图片点击放大
        ivImage.setOnClickListener(v -> {
            if (currentDiary.getImagePath() != null && !currentDiary.getImagePath().isEmpty()) {
                // TODO: 实现图片放大查看功能
                Toast.makeText(this, "图片查看功能待实现", Toast.LENGTH_SHORT).show();
            }
        });
    }
    
    private void shareDiary() {
        if (currentDiary == null) return;
        
        StringBuilder shareText = new StringBuilder();
        shareText.append("【").append(currentDiary.getTitle()).append("】\n\n");
        shareText.append(currentDiary.getContent()).append("\n\n");
        shareText.append("心情：").append(currentDiary.getMood()).append("\n");
        shareText.append("天气：").append(currentDiary.getWeather()).append("\n");
        shareText.append("日期：").append(currentDiary.getDate());
        
        Intent shareIntent = new Intent(Intent.ACTION_SEND);
        shareIntent.setType("text/plain");
        shareIntent.putExtra(Intent.EXTRA_TEXT, shareText.toString());
        shareIntent.putExtra(Intent.EXTRA_SUBJECT, "分享日记：" + currentDiary.getTitle());
        
        startActivity(Intent.createChooser(shareIntent, "分享日记"));
    }
    
    private void showDeleteConfirmDialog() {
        new AlertDialog.Builder(this)
                .setTitle("删除日记")
                .setMessage("确定要删除这篇日记吗？删除后无法恢复。")
                .setPositiveButton("删除", (dialog, which) -> deleteDiary())
                .setNegativeButton("取消", null)
                .show();
    }
    
    private void deleteDiary() {
        if (currentDiary == null) return;
        
        diaryViewModel.delete(currentDiary);
        Toast.makeText(this, "日记已删除", Toast.LENGTH_SHORT).show();
        finish();
    }
    
    // 从文件加载手写内容
    private void loadHandwritingFromFile(String handwritingPath) {
        if (TextUtils.isEmpty(handwritingPath) || handwritingView == null) {
            Log.d("DiaryReadActivity", "手写路径为空或handwritingView为null");
            return;
        }

        try {
            File file = new File(handwritingPath);
            Log.d("DiaryReadActivity", "尝试加载手写文件: " + handwritingPath);
            Log.d("DiaryReadActivity", "文件是否存在: " + file.exists());
            
            if (file.exists()) {
                Bitmap bitmap = BitmapFactory.decodeFile(handwritingPath);
                if (bitmap != null) {
                    Log.d("DiaryReadActivity", "成功加载bitmap，尺寸: " + bitmap.getWidth() + "x" + bitmap.getHeight());
                    handwritingView.setReadOnly(true); // 设置为只读模式
                    handwritingView.loadFromBitmap(bitmap);
                    Log.d("DiaryReadActivity", "已调用handwritingView.loadFromBitmap");
                } else {
                    Log.e("DiaryReadActivity", "无法解码bitmap文件");
                }
            } else {
                Log.e("DiaryReadActivity", "手写文件不存在: " + handwritingPath);
            }
        } catch (Exception e) {
            Log.e("DiaryReadActivity", "加载手写内容失败", e);
            e.printStackTrace();
            Toast.makeText(this, "加载手写内容失败", Toast.LENGTH_SHORT).show();
        }
    }
    
    @Override
    protected void onResume() {
        super.onResume();
        // 重新加载数据，以防在编辑页面有修改
        if (currentDiary != null) {
            loadDiaryData();
        }
    }
    
    // 播放背景音乐
    private void playBackgroundMusic(String musicPath) {
        // 如果没有音乐路径，直接返回
        if (TextUtils.isEmpty(musicPath)) {
            Log.d("DiaryReadActivity", "音乐路径为空，跳过播放");
            return;
        }
        
        Log.d("DiaryReadActivity", "尝试播放音乐，路径: " + musicPath);
        Log.d("DiaryReadActivity", "路径长度: " + musicPath.length());
        Log.d("DiaryReadActivity", "是否为content URI: " + musicPath.startsWith("content://"));
        
        // 停止之前的音乐播放
        stopBackgroundMusic();
        
        try {
            mediaPlayer = new MediaPlayer();
            
            // 检查音乐路径格式并设置数据源
            if (musicPath.startsWith("content://")) {
                Log.d("DiaryReadActivity", "使用content URI设置数据源");
                Uri musicUri = Uri.parse(musicPath);
                Log.d("DiaryReadActivity", "解析后的URI: " + musicUri.toString());
                
                // 检查是否有持久化权限
                boolean hasPermission = false;
                try {
                    // 尝试检查持久化权限
                    int flags = getContentResolver().getPersistedUriPermissions().stream()
                        .filter(permission -> permission.getUri().equals(musicUri))
                        .mapToInt(permission -> permission.isReadPermission() ? Intent.FLAG_GRANT_READ_URI_PERMISSION : 0)
                        .findFirst()
                        .orElse(0);
                    
                    hasPermission = (flags & Intent.FLAG_GRANT_READ_URI_PERMISSION) != 0;
                    Log.d("DiaryReadActivity", "持久化权限检查结果: " + hasPermission);
                } catch (Exception e) {
                    Log.w("DiaryReadActivity", "无法检查持久化权限", e);
                }
                
                if (!hasPermission) {
                    // 尝试验证content URI是否可访问
                    try {
                        getContentResolver().openInputStream(musicUri).close();
                        Log.d("DiaryReadActivity", "content URI验证成功（临时权限）");
                    } catch (Exception e) {
                        Log.e("DiaryReadActivity", "content URI验证失败", e);
                        Toast.makeText(this, "音乐文件无法访问，请重新选择音乐文件", Toast.LENGTH_LONG).show();
                        return;
                    }
                }
                
                mediaPlayer.setDataSource(this, musicUri);
            } else {
                Log.d("DiaryReadActivity", "使用文件路径设置数据源");
                
                // 验证文件路径
                File musicFile = new File(musicPath);
                Log.d("DiaryReadActivity", "文件是否存在: " + musicFile.exists());
                Log.d("DiaryReadActivity", "文件是否可读: " + musicFile.canRead());
                Log.d("DiaryReadActivity", "文件大小: " + musicFile.length() + " bytes");
                
                if (!musicFile.exists()) {
                    Log.e("DiaryReadActivity", "音乐文件不存在");
                    Toast.makeText(this, "音乐文件不存在", Toast.LENGTH_SHORT).show();
                    return;
                }
                
                if (!musicFile.canRead()) {
                    Log.e("DiaryReadActivity", "无法读取音乐文件");
                    Toast.makeText(this, "无法读取音乐文件", Toast.LENGTH_SHORT).show();
                    return;
                }
                
                mediaPlayer.setDataSource(musicPath);
            }
            
            Log.d("DiaryReadActivity", "开始异步准备MediaPlayer");
            mediaPlayer.prepareAsync(); // 使用异步准备
            
            mediaPlayer.setOnPreparedListener(mp -> {
                Log.d("DiaryReadActivity", "MediaPlayer准备完成，开始播放");
                mp.start();
                Toast.makeText(this, "背景音乐开始播放", Toast.LENGTH_SHORT).show();
            });
            
            mediaPlayer.setOnErrorListener((mp, what, extra) -> {
                Log.e("DiaryReadActivity", "MediaPlayer错误: what=" + what + ", extra=" + extra);
                String errorMsg = "音乐播放失败";
                switch (what) {
                    case MediaPlayer.MEDIA_ERROR_IO:
                        errorMsg = "音乐文件读取错误，可能文件已被删除或移动";
                        break;
                    case MediaPlayer.MEDIA_ERROR_MALFORMED:
                        errorMsg = "音乐文件格式错误";
                        break;
                    case MediaPlayer.MEDIA_ERROR_UNSUPPORTED:
                        errorMsg = "不支持的音乐格式";
                        break;
                    case MediaPlayer.MEDIA_ERROR_TIMED_OUT:
                        errorMsg = "音乐加载超时";
                        break;
                    default:
                        errorMsg = "音乐播放失败，请重新选择音乐文件";
                        break;
                }
                Toast.makeText(this, errorMsg, Toast.LENGTH_LONG).show();
                return true;
            });

            mediaPlayer.setOnCompletionListener(mp -> {
                Log.d("DiaryReadActivity", "音乐播放完成");
            });
            
        } catch (SecurityException e) {
            Log.e("DiaryReadActivity", "权限错误", e);
            Toast.makeText(this, "没有访问音乐文件的权限，请重新选择音乐文件", Toast.LENGTH_LONG).show();
        } catch (IllegalArgumentException e) {
            Log.e("DiaryReadActivity", "参数错误", e);
            Toast.makeText(this, "音乐文件路径无效，请重新选择音乐文件", Toast.LENGTH_LONG).show();
        } catch (IllegalStateException e) {
            Log.e("DiaryReadActivity", "MediaPlayer状态错误", e);
            Toast.makeText(this, "音乐播放器状态异常", Toast.LENGTH_SHORT).show();
        } catch (Exception e) {
            Log.e("DiaryReadActivity", "设置音乐数据源失败", e);
            e.printStackTrace();
            Toast.makeText(this, "音乐播放失败，请重新选择音乐文件", Toast.LENGTH_LONG).show();
            
            // 清理失败的MediaPlayer
            if (mediaPlayer != null) {
                try {
                    mediaPlayer.release();
                } catch (Exception releaseException) {
                    Log.e("DiaryReadActivity", "释放MediaPlayer失败", releaseException);
                }
                mediaPlayer = null;
            }
        }
    }
    
    // 停止背景音乐
    private void stopBackgroundMusic() {
        if (mediaPlayer != null) {
            try {
                if (mediaPlayer.isPlaying()) {
                    mediaPlayer.stop();
                }
                mediaPlayer.release();
            } catch (Exception e) {
                Log.e("DiaryReadActivity", "停止音乐播放失败", e);
            } finally {
                mediaPlayer = null;
            }
        }
    }
    
    @Override
    protected void onPause() {
        super.onPause();
        // 暂停音乐播放
        if (mediaPlayer != null && mediaPlayer.isPlaying()) {
            mediaPlayer.pause();
        }
    }
    
    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 释放音乐播放器资源
        stopBackgroundMusic();
    }
}